<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Breview extends Controller
{
	private $_template_f;
	private $_folderImageStore = 'uploads/images/';
	
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->load->language('common', $this->_lang);
		$common_lang = $this->lang->line('common_lang');	
		if(!$this->session->userdata('uname'))
		{
			redirect(site_url('login/'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		
		$this->_template_f = $this->config->item('template_f');
		$this->load->language('breview/breview', $this->_lang);
		$this->load->helper('breadcrumb');
        $this->load->model('breview/breview_model');
	}
	
	function index()
	{
		$this->review();
	}
	
	function review()
	{
		$data = array();
		$data['lang'] = $this->lang->line('breview');
		
		$uri = $this->uri->ruri_to_assoc(1);
		
		$filter = 'new';
		$uid = (int)$this->session->userdata('uid');
		if(array_key_exists('uid', $uri) && (int)$uri['uid'] > 0) $uid = (int)$uri['uid'];
		if(array_key_exists('filter', $uri)) $filter = $uri['filter'];
		
		//phan trang
		$limit = 10;
		if(array_key_exists('limit', $uri)) $limit = $uri['limit'];		
		$page = 1;
		if(array_key_exists('page', $uri)) $page = $uri['page'];
		if($page < 1) $page = 1;
		
		$get_data = $this->breview_model->list_banner_processing2($uid,$filter,$page,$limit);
			
		$total_page = $get_data['total_page'];
		if($page > $total_page) $page = $total_page;
		
		$data['lstBanner'] = $get_data['bList'];
		
		$this->load->library('mycommon');

		for ($i = 0; $i < count($data['lstBanner']); $i++)
		{
			$banner = &$data['lstBanner'][$i];
			$banner['filename'] = $this->mycommon->getBannerImagPath('', '', $banner['filename'], strtotime($banner['createtime']));
		}
		
		$this->session->set_userdata('br_page', $this->uri->ruri_string());
				
		$data['filter'] = $filter;
		$data['limit'] = $limit;
		$data['page'] = $page;
		$data['total_page'] = $total_page;
		$sum_banner_status = $get_data['status'];
		$data['sum_all_banner'] = $sum_banner_status[0][0]+$sum_banner_status[1][0]+$sum_banner_status[2][0];
		$data['sum_new_banner'] = $sum_banner_status[0][0];
		$data['sum_old_banner'] = $sum_banner_status[2][0]+$sum_banner_status[1][0];
		$data['publishers'] = $this->breview_model->publisher_list();
		$data['uid'] = $uid;
		
		$this->_loadHeader('Self serving - Banner review');
		$this->_loadMenu();

		$this->load->view($this->_template_f . 'breview/view', $data);
		
		$this->_loadFooter();
	}
	
	function change_publisher()
	{
		if(isset($_POST['banner']))
		{
			$lang = $this->lang->line('breview');
			
			$lsBreview = trim($this->input->post('banner', true));
			$lsBreview = array_filter(explode(',', $lsBreview));

			$uid = $this->input->post('uid', true);
			if(is_array($uid)) $uid = (int)$uid[0];
			else $uid = (int)$uid;
			
			$publisherInfo = $this->breview_model->get_user_info($uid);
			
			if(count($lsBreview) > 0)
			{
				foreach($lsBreview as $bannerid)
				{
					$bannerInfo = $this->breview_model->get_banner_info((int)$bannerid);
					//Send mail cho publisher
					$this->sendmail($bannerInfo['bInfo'], $publisherInfo);
				}
				//Update database
				$this->breview_model->publisher_change(implode(',', $lsBreview), $uid);
				echo $lang['update_success'];
			}
		}
	}
	
	function uploadImageFTP(&$bannerInfo)
 	{
 		$lang = $this->lang->line('breview_lang');
 		
 		$createdTime = date($bannerInfo['bInfo']['createtime']);
		$createdTimeInfo = getdate(strtotime($createdTime));
		$yearFolder = $createdTimeInfo['year'];
		$monthFolder = $createdTimeInfo['mon'];
		$monthFolder = ($monthFolder < 10) ? "0" . $monthFolder : $monthFolder;
 		
 		// ftp file to image server
        //ftp config and connect
        $configFTP['hostname'] = FTP_IMG_HOST;
        $configFTP['username'] = FTP_IMG_USER;
        $configFTP['password'] = FTP_IMG_PASS;	
        if(!$this->myftp->connect($configFTP))
        {
        	$this->myftp->close();
        	echo $data['ErrorMess'] = $lang['ftp_connect_err'];
        }
        else
        {
            // check folder exists
           // check year folder
            $ftpFolder = FTP_IMG_REAL_PATH . $yearFolder . '/';
            if(!$this->myftp->changedir($ftpFolder))
            {
            	$this->myftp->mkdir($ftpFolder, 0755);
            }
            // check month folder
            $ftpFolder = $ftpFolder . $monthFolder . '/';
            if(!$this->myftp->changedir($ftpFolder))
            {
            	$this->myftp->mkdir($ftpFolder, 0755);
            }
                        
          	// ftp file len server cpc image
            $localImageFilePath = $this->_folderImageStore . $yearFolder . '/' . $monthFolder . '/' . $bannerInfo['bInfo']['filename'];
			$ftpCampFileImage = $ftpFolder . $bannerInfo['bInfo']['filename'];                        
			
			if(!$this->myftp->upload($localImageFilePath, $ftpCampFileImage, FTP_BINARY, 0755))
            {
                //$data['ErrorMess'] = 'Can not FPT image to server!';
            }
            //else echo 'Upload ftp thanh cong';
        }
 	}
 	
	function sendmail(&$banner, &$publisher)
	{
		$this->load->language('email_tpl', $this->_lang);
		
		$emal_tpl_language = $this->lang->line('email_tpl_lang');
		$b_lang = $this->lang->line('breview');
		
		$data = array();
		
		//Tao duong dan banner image
		$createdTime = date($banner['createtime']);
		$createdTimeInfo = getdate(strtotime($createdTime));
		$yearFolder = $createdTimeInfo['year'];
		$monthFolder = $createdTimeInfo['mon'];
		$monthFolder = ($monthFolder < 10) ? "0" . $monthFolder : $monthFolder;
		$localImageFilePath = $this->_folderImageStore . $yearFolder . '/' . $monthFolder . '/' . $banner['filename'];
		
		//Gui mail
		$data['syttem_name'] = $this->config->item('serving_email_name');
		$data['syttem_title'] = $b_lang['access_mail_subject'];
		$data['langcode'] = $this->_lang; 
		$data['report_lang'] = $emal_tpl_language['ad_accepted_alert'];
		
		$base_url = str_replace('/admin', '', base_url());
		
		$data['link'] = array(
			'imagepath' => $base_url.'images/email/',
			'home'=> $base_url,
			'login' => str_replace('/admin', '', site_url('login'))
		);
		
		$data['bannerInfo'] = array(
			'title' => $banner['bannername'],
			'domain' => $this->getDomain($banner['url']),
			'bodytext' =>	$banner['description'],
			'image' => $base_url.$localImageFilePath
		);
		
		$data['mess_info'] = array(			
			'content' => $b_lang['access_mail_info']
		);
		
		
		$emailConfig['mailtype'] = 'html';
		$this->load->library('email', $emailConfig);
		
		$email_subject = $data['syttem_name'].' - '.$data['syttem_title'];
		$email_content = $this->load->view($this->_template_f . 'emailtpl/email_ad_accepted_alert_view', $data, true);
		$this->email->clear();
		$this->email->from($this->config->item('serving_email'), $data['syttem_name']);
		$this->email->to($publisher['email_address']);
		//$this->email->cc($publisher['email_address']);
		$this->email->subject($email_subject);
		$this->email->message($email_content);
		$this->email->send();
		$this->email->clear();
	}
	
	function getDomain($strUrl)
	{
		$strUrl = trim($strUrl);
		if($strUrl == '') return '';
		$parse = parse_url($strUrl);
		return $parse['host'];
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
		$header['module_name'] = 'breview';
		$header['lang'] = $this->_lang;
		$header['common_lang'] = $this->lang->line('common_lang');
        
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		
		 //load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
	
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
        
		$this->load->view($this->_template_f . 'menu_view',$data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
}